/**
 * API工具函数
 * 包含各种辅助函数和工具方法
 */

import AsyncStorage from '@react-native-async-storage/async-storage';
import { STORAGE_KEYS } from './config';

/**
 * Token管理工具
 */
export const tokenUtils = {
  // 设置Token
  setTokens: async (accessToken, refreshToken) => {
    try {
      await AsyncStorage.multiSet([
        [STORAGE_KEYS.ACCESS_TOKEN, accessToken],
        [STORAGE_KEYS.REFRESH_TOKEN, refreshToken || ''],
      ]);
      return true;
    } catch {
      return false;
    }
  },

  // 获取Token
  getAccessToken: async () => {
    try {
      return await AsyncStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);
    } catch {
      return null;
    }
  },

  // 获取刷新Token
  getRefreshToken: async () => {
    try {
      return await AsyncStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);
    } catch {
      return null;
    }
  },

  // 清除Token
  clearTokens: async () => {
    try {
      await AsyncStorage.multiRemove([
        STORAGE_KEYS.ACCESS_TOKEN,
        STORAGE_KEYS.REFRESH_TOKEN,
        STORAGE_KEYS.USER_INFO,
      ]);
      return true;
    } catch {
      return false;
    }
  },

  // 检查Token是否存在
  hasToken: async () => {
    try {
      const token = await AsyncStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);
      return !!token;
    } catch {
      return false;
    }
  },

  // 解析Token（如果是JWT）
  parseToken: token => {
    try {
      if (!token) return null;

      const parts = token.split('.');
      if (parts.length !== 3) return null;

      const payload = JSON.parse(atob(parts[1]));
      return payload;
    } catch {
      return null;
    }
  },

  // 检查Token是否过期
  isTokenExpired: token => {
    try {
      const payload = tokenUtils.parseToken(token);
      if (!payload || !payload.exp) return true;

      const currentTime = Math.floor(Date.now() / 1000);
      return payload.exp < currentTime;
    } catch {
      return true;
    }
  },
};

/**
 * URL工具函数
 */
export const urlUtils = {
  // 构建URL
  buildURL: (baseURL, path, params = {}) => {
    let url = `${baseURL}${path}`;

    // 替换路径参数
    Object.keys(params).forEach(key => {
      url = url.replace(`:${key}`, encodeURIComponent(params[key]));
    });

    return url;
  },

  // 构建查询字符串
  buildQueryString: params => {
    if (!params || Object.keys(params).length === 0) {
      return '';
    }

    const queryString = Object.keys(params)
      .filter(
        key =>
          params[key] !== undefined &&
          params[key] !== null &&
          params[key] !== '',
      )
      .map(key => {
        const value = params[key];
        if (Array.isArray(value)) {
          return value
            .map(v => `${encodeURIComponent(key)}=${encodeURIComponent(v)}`)
            .join('&');
        }
        return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
      })
      .join('&');

    return queryString ? `?${queryString}` : '';
  },

  // 解析查询字符串
  parseQueryString: queryString => {
    const params = {};
    if (!queryString) return params;

    const pairs = queryString.replace(/^\?/, '').split('&');
    pairs.forEach(pair => {
      const [key, value] = pair.split('=');
      if (key) {
        params[decodeURIComponent(key)] = decodeURIComponent(value || '');
      }
    });

    return params;
  },
};

/**
 * 数据转换工具
 */
export const dataUtils = {
  // 深拷贝
  deepClone: obj => {
    if (obj === null || typeof obj !== 'object') return obj;
    if (obj instanceof Date) return new Date(obj.getTime());
    if (obj instanceof Array) return obj.map(item => dataUtils.deepClone(item));
    if (typeof obj === 'object') {
      const clonedObj = {};
      Object.keys(obj).forEach(key => {
        clonedObj[key] = dataUtils.deepClone(obj[key]);
      });
      return clonedObj;
    }
  },

  // 移除空值
  removeEmptyValues: obj => {
    const result = {};
    Object.keys(obj).forEach(key => {
      const value = obj[key];
      if (value !== null && value !== undefined && value !== '') {
        result[key] = value;
      }
    });
    return result;
  },

  // 扁平化对象
  flattenObject: (obj, prefix = '') => {
    const flattened = {};

    Object.keys(obj).forEach(key => {
      const value = obj[key];
      const newKey = prefix ? `${prefix}.${key}` : key;

      if (
        value !== null &&
        typeof value === 'object' &&
        !Array.isArray(value)
      ) {
        Object.assign(flattened, dataUtils.flattenObject(value, newKey));
      } else {
        flattened[newKey] = value;
      }
    });

    return flattened;
  },

  // 转换为FormData
  toFormData: (obj, formData = new FormData(), prefix = '') => {
    Object.keys(obj).forEach(key => {
      const value = obj[key];
      const formKey = prefix ? `${prefix}[${key}]` : key;

      if (value instanceof File || value instanceof Blob) {
        formData.append(formKey, value);
      } else if (Array.isArray(value)) {
        value.forEach((item, index) => {
          if (typeof item === 'object') {
            dataUtils.toFormData(item, formData, `${formKey}[${index}]`);
          } else {
            formData.append(`${formKey}[${index}]`, item);
          }
        });
      } else if (value !== null && typeof value === 'object') {
        dataUtils.toFormData(value, formData, formKey);
      } else if (value !== null && value !== undefined) {
        formData.append(formKey, value);
      }
    });

    return formData;
  },
};

/**
 * 缓存工具
 */
export const cacheUtils = {
  // 设置缓存
  setCache: async (key, data, expireTime = 3600000) => {
    // 默认1小时
    try {
      const cacheData = {
        data,
        timestamp: Date.now(),
        expireTime,
      };
      await AsyncStorage.setItem(`cache_${key}`, JSON.stringify(cacheData));
      return true;
    } catch {
      return false;
    }
  },

  // 获取缓存
  getCache: async key => {
    try {
      const cacheString = await AsyncStorage.getItem(`cache_${key}`);
      if (!cacheString) return null;

      const cacheData = JSON.parse(cacheString);
      const now = Date.now();

      // 检查是否过期
      if (now - cacheData.timestamp > cacheData.expireTime) {
        await AsyncStorage.removeItem(`cache_${key}`);
        return null;
      }

      return cacheData.data;
    } catch {
      return null;
    }
  },

  // 清除缓存
  clearCache: async key => {
    try {
      await AsyncStorage.removeItem(`cache_${key}`);
      return true;
    } catch {
      return false;
    }
  },

  // 清除所有缓存
  clearAllCache: async () => {
    try {
      const keys = await AsyncStorage.getAllKeys();
      const cacheKeys = keys.filter(key => key.startsWith('cache_'));
      await AsyncStorage.multiRemove(cacheKeys);
      return true;
    } catch {
      return false;
    }
  },
};

/**
 * 错误处理工具
 */
export const errorUtils = {
  // 格式化错误信息
  formatError: error => {
    if (typeof error === 'string') {
      return { message: error, code: 'UNKNOWN' };
    }

    if (error.response) {
      return {
        message: error.message || '请求失败',
        code: error.response.status || 'UNKNOWN',
        data: error.response.data,
      };
    }

    return {
      message: error.message || '未知错误',
      code: error.code || 'UNKNOWN',
    };
  },

  // 检查是否为网络错误
  isNetworkError: error => {
    return (
      !error.response &&
      error.message &&
      (error.message.includes('Network') ||
        error.message.includes('timeout') ||
        error.message.includes('连接'))
    );
  },

  // 检查是否为服务器错误
  isServerError: error => {
    return error.response && error.response.status >= 500;
  },

  // 检查是否为客户端错误
  isClientError: error => {
    return (
      error.response &&
      error.response.status >= 400 &&
      error.response.status < 500
    );
  },
};

/**
 * 文件处理工具
 */
export const fileUtils = {
  // 获取文件扩展名
  getFileExtension: filename => {
    return filename.split('.').pop()?.toLowerCase() || '';
  },

  // 检查文件类型
  isImageFile: filename => {
    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
    return imageExtensions.includes(fileUtils.getFileExtension(filename));
  },

  isAudioFile: filename => {
    const audioExtensions = ['mp3', 'wav', 'aac', 'ogg', 'm4a'];
    return audioExtensions.includes(fileUtils.getFileExtension(filename));
  },

  isVideoFile: filename => {
    const videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm'];
    return videoExtensions.includes(fileUtils.getFileExtension(filename));
  },

  // 格式化文件大小
  formatFileSize: bytes => {
    if (bytes === 0) return '0 B';

    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  },
};

/**
 * 验证工具
 */
export const validateUtils = {
  // 验证邮箱
  isValidEmail: email => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  },

  // 验证手机号
  isValidPhone: phone => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  },

  // 验证URL
  isValidURL: url => {
    try {
      new URL(url);
      return true;
    } catch {
      return false;
    }
  },

  // 验证必填字段
  validateRequired: (data, requiredFields) => {
    const errors = {};

    requiredFields.forEach(field => {
      if (
        !data[field] ||
        (typeof data[field] === 'string' && data[field].trim() === '')
      ) {
        errors[field] = `${field}是必填字段`;
      }
    });

    return {
      isValid: Object.keys(errors).length === 0,
      errors,
    };
  },
};

/**
 * 导出所有工具
 */
export default {
  token: tokenUtils,
  url: urlUtils,
  data: dataUtils,
  cache: cacheUtils,
  error: errorUtils,
  file: fileUtils,
  validate: validateUtils,
};
